import { genDefDate } from '../../utils/DateUtils';
import { genCloudFilePath } from '../../utils/CloudUtils';

const app=getApp();
const MAPKEY ='EGQBZ-NS7WP-IJZDZ-L653M-2NCDE-2BB22';
const referer='存时宝';
const location = JSON.stringify({
  latitude:39.89631551,
  longitude:116.323459711
});
const category='';
const chooseLocationPlugin = requirePlugin('chooseLocation');

//页面的初始数据
Page({
  data:{
    name:'',
    phone:null,
    num:1,
    location:{},
    startDate: genDefDate(),
    endDate: genDefDate(),
    startTime: '09:30',
    endTime: '18:00',
    // region: ['广东省', '珠海市', '斗门区'],
    title:'',
    tag:'',
    desc:'',
    requirements:'',
    imgList: [],
  },  

  bindKeyInput(e){
    const key = e.currentTarget.dataset.key;
    let data={};
    data[key] = e.detail.value;
    this.setData(data);
  },
  bindNumInput(e) {

    const key = e.currentTarget.dataset.key;
    let data = {};
    data[key] = Number(e.detail.value);
    this.setData(data);

  },
  startTimeChange(e) {
    this.setData({
      startTime: e.detail.value
    })
  },
  endTimeChange(e) {
    this.setData({
      endTime: e.detail.value
    })
  },

  startDateChange(e) {
    this.setData({
      startDate: e.detail.value
    })
  },
  endDateChange(e) {
    this.setData({
      endDate: e.detail.value
    })
  },


  
  onShow() {
    const location = chooseLocationPlugin.getLocation();
    if (location) {
      console.log(location);
      this.setData({ location: location });
    }else{
      console.log("get location fail")
    }

  },



  chooseLocation(e){
    wx.navigateTo({
      url: 'plugin://chooseLocation/index?key='+MAPKEY+'&referer='+referer+'&category='+category
    });
  
  },

  uploadImg(filePath) { // 调用wx.cloud.uploadFile上传文件
    return wx.cloud.uploadFile({
      cloudPath: genCloudFilePath(filePath),
      filePath: filePath
    })
  },
  ChooseImage() {
    const count = 1 - this.data.imgList.length; //最多1张图片
    if (count < 1) {
      return;
    }
    wx.chooseImage({
      count: count, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album','camera'], //从相册选择
      success: (res) => {
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    });
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '操作确认',
      content: '确定要删除这张照片吗？',
      cancelText: '取消',
      confirmText: '删除',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },

  saveData(data) {
    wx.showLoading({
      title: '发布中'
    });
    const uploadTasks = data.imgList.map(item => this.uploadImg(item))
    Promise.all(uploadTasks).then(result => {
      console.log(result);
      const imgList = result.map(img => (img.fileID));
      data.imgList = imgList;
      console.log(data);
      const db = wx.cloud.database();
      // data.geo = db.Geo.Point(data.location.longitude, data.location.latitude);
      db.collection('taskList').add({
        data: data
      }).then(result => {
        console.log('保存成功', result)
        wx.hideLoading()
        wx.showToast({
          title: '发布成功',
          duration: 2000
        })
        setTimeout(() => {
          wx.redirectTo({
            url: '/pages/admin/admin',
          })
        }, 2000);
      }).catch(() => {
        wx.hideLoading()
        wx.showToast({
          title: '发布失败',
          icon: 'error'
        })
      })

    }).catch(() => {
      wx.hideLoading()
      wx.showToast({
        title: '上传图片错误',
        icon: 'error'
      })
    })
  },
  

  publish() {
    console.log("tapPublish");
    // if (this.checkLogin() == false) {
    //   return;
    // }
    let data = {};
    let errorMsg = "";
    data.name=this.data.name;
    data.phone=this.data.phone; 
    data.num=this.data.num;
    data.location = this.data.location;
    data.startDate = this.data.startDate;
    data.endDate = this.data.endDate;
    data.startTime = this.data.startTime;
    data.endTime = this.data.endTime;
    data.title = this.data.title;
    data.tag=this.data.tag;
    data.desc=this.data.desc;
    data.requirements = this.data.requirements;
    data.imgList = this.data.imgList;
   
 


    if (data.imgList.length < 1) {
      errorMsg = '至少上传一张照片';
    }
    if (data.title == "" || data.desc == ""||data.requirements ==""||data.tag =="") {
      errorMsg = '请完善活动信息';
    }
    if (isNaN(data.phone) || isNaN(data.num)) {
      errorMsg = "手机号码或者人数只能输入纯数字";
    }
    if (errorMsg) {
      wx.showToast({
        title: errorMsg,
        icon: 'none'
      })
      return;
    }

    this.saveData(data);
  },

})